package org.damocode.iot.network.udp;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.californium.elements.Connector;
import org.eclipse.californium.elements.UDPConnector;

/**
 * @Description: Upd服务提供器
 * @Author: zzg
 * @Date: 2022/7/22 15:40
 * @Version: 1.0.0
 */
@Slf4j
public class UdpSupportProvider {

    public DefaultUdpSupport createNetwork(UdpSupportProperties properties) {
        DefaultUdpSupport udpSupport = new DefaultUdpSupport(properties.getId());
        initUpdSupport(udpSupport, properties);
        return udpSupport;
    }

    private Connector createConnector(UdpSupportProperties properties) {
        UDPConnector connector = new UDPConnector(properties.createLocalAddress());
        connector.setReceiverPacketSize(properties.getReceiverPacketSize());
        return connector;
    }

    private void initUpdSupport(DefaultUdpSupport support, UdpSupportProperties properties) {
        try {
            Connector connector = createConnector(properties);
            support.setConnector(connector);
            support.setAddress(properties.createRemoteAddress());
            support.setBindAddress(properties.createLocalAddress());
        } catch (Throwable e) {
            support.setLastError(e.getMessage());
            throw e;
        }
    }

}
